package play;

/**
 * @Info:
 * @Author: 唐小尊
 * @Date: 2020/10/20 09:38
 */
public class MyMath {
    public static void main(String[] args) {
        System.out.println(sqrt_2(16.0));
    }

    public static double sqrt_1(double t, Double precise) {
        double low = 0, high = t, middle, squre,
                prec = precise != null ? precise : 1e-7;
        if (t < 0) {
            throw new RuntimeException("Negetive number cannot have a sqrt root.");
        }

        while (high - low > prec) {
            middle = (low + high) / 2;
            squre = middle * middle;

            if (squre > t) {
                high = middle;
            } else {
                low = middle;
            }
        }
        return (low + high) / 2;
    }

    public static double sqrt_2(Double precise) {
        if (precise == 0) {
            return 0;
        }
        double last = 0.0;
        double res = 1.0;
        while (res != last) {
            last = res;
            res = (res + precise / res) / 2;
        }
        return res;
    }

    public static float sqrtRoot(float m) {
        if (m == 0) {
            return 0;
        }

        float i = 0;
        float x1, x2 = 0;
        //找到最接近的小数点后一位的数
        while ((i * i) <= m) {
            i += 0.1;
        }
        x1 = i;
        //
        for (int j = 0; j < 10; j++) {
            x2 = m;
            x2 /= x1;
            x2 += x1;
            x2 /= 2;
            x1 = x2;
        }
        return x2;
    }
}
